package com.allinpay.merchantweb.controller;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.bootdo.common.annotation.Log;
//import com.bootdo.common.config.Constant;
//import com.bootdo.common.controller.BaseController;
//import com.bootdo.common.utils.R;
//import com.bootdo.system.domain.RoleDO;
//import com.bootdo.system.service.RoleService;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.allinpay.merchantweb.common.utils.StringUtil;
import com.allinpay.merchantweb.constants.InputCode;
import com.allinpay.merchantweb.model.CommRoleInfo;
import com.allinpay.merchantweb.model.CommRolePrivilege;
import com.allinpay.merchantweb.model.CommUserRole;
import com.allinpay.merchantweb.model.EnterpriseInfo;
import com.allinpay.merchantweb.model.PageForBootStrap;
import com.allinpay.merchantweb.model.PageForLayui;
import com.allinpay.merchantweb.response.ResponseData;
import com.allinpay.merchantweb.service.ICommPrivilegeService;
import com.allinpay.merchantweb.service.IEnterpriseInfoService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;

@RequestMapping("/role")
@Controller
public class RoleController extends BaseController {
	
	private final static  Logger log = LoggerFactory.getLogger(RoleController.class);
	
	String prefix = "setting/role";
	@Autowired
	ICommPrivilegeService commPrivilegeService;
	
	@Autowired 
	IEnterpriseInfoService enterpriseInfoService;
	
//	@RequiresPermissions("sys:role:role")
	@GetMapping()
	String role() {
		return prefix + "/role";
	}
	
	@GetMapping("/test")
	String test() {
		return prefix + "/test";
	}

//	@RequiresPermissions("sys:role:role")
	@GetMapping("/enterpriseList")
	@ResponseBody()
	Object enterpriseList() {
		Object retObject = null;
		try {
			retObject = enterpriseInfoService.queryEnterpriseInfo(null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	@GetMapping("/compPrivilegeList")
	@ResponseBody()
	Object compPrivilegeList() {
		Object retObject = null;
		try {
			retObject = commPrivilegeService.queryCompPrivilege();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	@GetMapping("/allinpayPrivilege")
	@ResponseBody()
	Object allinpayPrivilege() {
		Object retObject = null;
		try {
			retObject = commPrivilegeService.queryAllinpayPrivilege();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	@GetMapping("/getPrivilegesByAccount")
	@ResponseBody()
	Object getPrevilegesByAccount() {
		Object retObject = null;
		try {
			retObject = commPrivilegeService.getPrivilegesByAccount("tlxt001");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	@GetMapping("/getEntryMenuTreeByAccount")
	@ResponseBody()
	Object getEntryMenuTreeByAccount() {
		Object retObject = null;
		try {
			retObject = commPrivilegeService.getEntryMenuTreeByAccount("tlxt001");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return new Gson().toJson(retObject);
	}
	
	
	@GetMapping("/queryUserRoleList")
	@ResponseBody()
	Object queryUserRoleList(CommUserRole commUserRole) {
		Object retObject = null;
		if( commUserRole == null) {
			commUserRole = new CommUserRole();
			commUserRole.setPageNum(1);
			commUserRole.setNumPerPage(10);
		}
		try {
			retObject = commPrivilegeService.queryUserRoleList(commUserRole);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	
	@GetMapping("/queryCheckedPrivileges/{roleType}/{roleId}")
	@ResponseBody()
	Object queryUserRoleList(@PathVariable Integer roleType, @PathVariable Integer roleId) {
		Object retObject = null;
		try {
			CommRolePrivilege commRolePrivilege = new CommRolePrivilege();
			commRolePrivilege.setRoleId(roleId);
			commRolePrivilege.setRoleType(roleId);
			retObject = commPrivilegeService.queryRolePrivilegeList(commRolePrivilege );
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	
	
	@PostMapping("/addRoleInfo")
	@ResponseBody()
	Object addRoleInfo(CommRoleInfo commRoleInfo, HttpServletRequest httpRequest) {
		
//		byte[] bytes = new byte[0];
//		ServletInputStream inputStream;
//		try {
//			inputStream = httpRequest.getInputStream();
//			bytes = new byte[inputStream.available()];
//			inputStream.read(bytes);
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		
//		Map<String, String[]> map = httpRequest.getParameterMap();
//		
//		String str = new String(bytes);
//		System.out.println("addRoleInfo commRoleInfo:" +
//				str
//				);
//		System.out.println("addRoleInfo map:" +
//				new Gson().toJson(map)
//				);
//		
//		System.out.println("addRoleInfo commPrivilegeInfo:" + new Gson().toJson(commRoleInfo));
		Object retObject = null;
		if( commRoleInfo == null) {
			return new PageForLayui("9","提交内容为空");
		}
		try {
			//'角色类型：1--一级管理员（通联管理员创建的角色） 2---普通管理员3.通联管理员',
			//get InstanceId from session
			//judge RoleType By InstanceId( from Allinpay using 1/3)
			if( commRoleInfo.getInstanceId() != 9999 ) {
				commRoleInfo.setRoleType(2);
			}else {
				commRoleInfo.setRoleType(1);
			}
			
			boolean addResult = commPrivilegeService.addRoleInfo(commRoleInfo);
			if ( addResult ) {
				retObject = new PageForLayui("0","add roldeInfo succ");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	
	@PostMapping("/updateRoleInfo")
	@ResponseBody()
	Object updateRoleInfo(CommRoleInfo commRoleInfo, HttpServletRequest httpRequest) {
		
		Object retObject = null;
		if( commRoleInfo == null) {
			return new PageForLayui("9","提交内容为空");
		}
		try {
			//'角色类型：1--一级管理员（通联管理员创建的角色） 2---普通管理员3.通联管理员',
			//get InstanceId from session
			//judge RoleType By InstanceId( from Allinpay using 1/3)
			if( commRoleInfo.getInstanceId() != 9999 ) {
				commRoleInfo.setRoleType(2);
			}else {
				commRoleInfo.setRoleType(1);
			}
			
			boolean addResult = commPrivilegeService.updateRoleInfo(commRoleInfo);
			if ( addResult ) {
				retObject = new PageForLayui("0","update roldeInfo succ");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	
	@PostMapping("/batchDeleteRoleInfo")
	@ResponseBody()
	Object batchDeleteRoleInfo( HttpServletRequest httpRequest) {
		
		byte[] bytes = new byte[0];
		ServletInputStream inputStream;
		try {
			inputStream = httpRequest.getInputStream();
			bytes = new byte[inputStream.available()];
			inputStream.read(bytes);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Map<String, String[]> map = httpRequest.getParameterMap();
		
		String str = new String(bytes);
		System.out.println("batchDeleteRoleInfo commRoleInfo:" +
				str
				);
		System.out.println("batchDeleteRoleInfo map:" +
				new Gson().toJson(map)
				);
		
		ArrayList<Integer> roleIdList = null;
		roleIdList = new Gson().fromJson(httpRequest.getParameter("roleIdList")
				, new TypeToken<ArrayList<Integer>>() {}.getType());
		
		System.out.println("batchDeleteRoleInfo roleIdList:" +
				roleIdList
				);
		Object retObject = null;
		if( roleIdList == null) {
			return new PageForLayui("9","提交内容为空");
		}
		try {
			
			boolean addResult = commPrivilegeService.batchDeleteRoleInfo(roleIdList);
			if ( addResult ) {
				retObject = new PageForLayui("0","add roldeInfo succ");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	@PostMapping("/deleteRoleInfo/{roleId}")
	@ResponseBody()
	Object deleteRoleInfo(@PathVariable Integer roleId) {
		
		
		Object retObject = null;
		if( roleId == null) {
			return new Object(){boolean state=false; String subCode="FFFF"; String subMsg = "提交内容为空";};
		}
		try {
			List<Integer> roleIdList = new ArrayList<Integer>(2);
			roleIdList.add(roleId);
			boolean addResult = commPrivilegeService.batchDeleteRoleInfo(roleIdList);
			
			if ( addResult ) {
				retObject = new PageForLayui("0","add roldeInfo succ");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	
	
	
	@GetMapping("/queryRoleInfoList")
	@ResponseBody()
	Object queryRoleInfoList(CommRoleInfo commRoleInfo) {
//		System.out.println("queryRoleInfoList commRoleInfo:" + new Gson().toJson(commRoleInfo));
		PageForBootStrap page = null;
		if( commRoleInfo == null) {
			commRoleInfo = new CommRoleInfo();
			commRoleInfo.setPageNum(1);
			commRoleInfo.setNumPerPage(10);
		}
		try {
			
			ResponseData respBean =	commPrivilegeService.queryRoleInfoList(commRoleInfo);
			page = new PageForBootStrap();
			page.setTotal(respBean.getTotal());
			page.setRows(respBean.getDataList());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return page;
	}
	
	
	@GetMapping("/queryRoleInfoList2")
	@ResponseBody()
	Object queryRoleInfoList2( HttpServletRequest httpRequest) {
//		byte[] bytes = new byte[0];
//		ServletInputStream inputStream;
//		try {
//			inputStream = httpRequest.getInputStream();
//			bytes = new byte[inputStream.available()];
//			inputStream.read(bytes);
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		
//		Map<String, String[]> map = httpRequest.getParameterMap();
//		
//		String str = new String(bytes);
//		System.out.println("queryRoleInfoList2 commRoleInfo:" +
//				str
//				);
//		System.out.println("queryRoleInfoList2 map:" +
//				new Gson().toJson(map)
//				);
		Object retObject = null;
		CommRoleInfo commRoleInfo = new CommRoleInfo();
		String sPageNum = httpRequest.getParameter("page");
		String sPageSize = httpRequest.getParameter("limit");
		String sRoleName = httpRequest.getParameter("roleName");
		if( !StringUtil.isEmpty(sPageNum) && !StringUtil.isEmpty(sPageSize)) {
			commRoleInfo.setPageNum(Integer.parseInt(sPageNum));
			commRoleInfo.setNumPerPage(Integer.parseInt(sPageSize));
		}
		if ( !StringUtil.isEmpty(sRoleName) ) {
			commRoleInfo.setRoleName(sRoleName);
		}
		
//		if( commRoleInfo == null) {
//			commRoleInfo = new CommRoleInfo();
//			commRoleInfo.setPageNum(1);
//			commRoleInfo.setNumPerPage(10);
//		}
		try {
			ResponseData respBean = commPrivilegeService.queryRoleInfoList(commRoleInfo);
			PageForLayui page = new PageForLayui();
			page.setCode("0");
			page.setMsg("succ");
			page.setCount(respBean.getTotal());
			page.setData(respBean.getDataList());
			
			retObject = page;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	

	// @Log("添加角色")
//	@RequiresPermissions("sys:role:add")
	@GetMapping("/add")
	String add(Model model) {
		model.addAttribute("aipInsList", InputCode.getDesc());
		return prefix + "/add";
	}
	
	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") int id, Model model) {
		Object retObject = null;
		try {
			CommRoleInfo commRoleInfo  = new CommRoleInfo();
			commRoleInfo.setRoleInfoId(id);
			ResponseData<CommRoleInfo> respBean = commPrivilegeService.queryRoleInfoList(commRoleInfo  );
			model.addAttribute("roleInfo", respBean.getDataList().get(0));
			
			EnterpriseInfo enterInfo = new EnterpriseInfo();
			enterInfo.setInstanceId( respBean.getDataList().get(0).getInstanceId());
			ResponseData<EnterpriseInfo> respEnterpriseBean = enterpriseInfoService.queryEnterpriseInfo(enterInfo);
			model.addAttribute("enterpriseName", respEnterpriseBean.getDataList().get(0).getEnterpriseName());
			
			CommRolePrivilege commRolePrivilege = new CommRolePrivilege();
			commRolePrivilege.setRoleId(commRoleInfo.getRoleInfoId());
			commRolePrivilege.setRoleType(
					respBean.getDataList().get(0).getRoleType() );
//			System.out.println("getRoleType:" + ((CommRoleInfo) respBean.getDataList().get(0)).getRoleType());
			Object retTree = commPrivilegeService.queryRolePrivilegeList(commRolePrivilege );
			
			model.addAttribute("privilegeTree", retTree);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return prefix + "/edit";
	}
	
	

////	// @Log("编辑角色")
//////	@RequiresPermissions("sys:role:edit")
//	@GetMapping("/edit/{id}")
//	String edit(@PathVariable("id") Long id, Model model) {
//		RoleDO roleDO = roleService.get(id);
//		model.addAttribute("role", roleDO);
//		return prefix + "/edit";
//	}
//
////	// @Log("保存角色")
//////	@RequiresPermissions("sys:role:add")
//	@PostMapping("/save")
//	@ResponseBody()
//	R save(RoleDO role) {
//		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
//		}
//		if (roleService.save(role) > 0) {
//			return R.ok();
//		} else {
//			return R.error(1, "保存失败");
//		}
//	}
//
//	// @Log("更新角色")
////	@RequiresPermissions("sys:role:edit")
//	@PostMapping("/update")
//	@ResponseBody()
//	R update(RoleDO role) {
//		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
//		}
//		if (roleService.update(role) > 0) {
//			return R.ok();
//		} else {
//			return R.error(1, "保存失败");
//		}
//	}
//
//	// @Log("删除角色")
////	@RequiresPermissions("sys:role:remove")
//	@PostMapping("/remove")
//	@ResponseBody()
//	R save(Long id) {
//		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
//		}
//		if (roleService.remove(id) > 0) {
//			return R.ok();
//		} else {
//			return R.error(1, "删除失败");
//		}
//	}
//	
////	@RequiresPermissions("sys:role:batchRemove")
//	// @Log("批量删除角色")
//	@PostMapping("/batchRemove")
//	@ResponseBody
//	R batchRemove(@RequestParam("ids[]") Long[] ids) {
//		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
//		}
//		int r = roleService.batchremove(ids);
//		if (r > 0) {
//			return R.ok();
//		}
//		return R.error();
//	}
}
